//
//  RequestManager.swift
//  CosClub
//
//  Created by 沙睿 on 2020/2/4.
//  Copyright © 2020 ios. All rights reserved.
//

import Foundation
import Moya
import Alamofire

let apiVersion = "v1.0.0"
extension BaseApi  {
    func parsing(dict: Dictionary<String, Any>) -> BaseModel<T>?{
        if let modelT = BaseModel<T>.deserialize(from: dict) {
            return modelT
        }
        return nil
    }
}

extension BaseModel: Error {
    
}

public struct BaseApi<T> {
    
    public init() {
        
    }
    public let provider = MoyaProvider<MultiTarget>(requestClosure: { (endpoint:Endpoint, done: @escaping MoyaProvider<MultiTarget>.RequestResultClosure) in
        do {
            var request = try endpoint.urlRequest()
            request.timeoutInterval = 15 //设置请求超时时间
            done(.success(request))
            
        } catch{ return }
    })
    
    public func request(
        _ target: TargetType,
        success successCallback: @escaping (T?) -> Void,
        failure failureCallback: @escaping (Error) -> Void
    ) {
        
        provider.request(MultiTarget(target)) { result in
            switch result {
            case let .success(response):
                do {
                    //如果数据返回成功则直接将结果转为JSON
                    _ = try response.filterSuccessfulStatusCodes()
                    
                    guard let dict = BaseApi.dataToDictionary(data: response.data) else {
                        print("解析失败")
                        return failureCallback(BaseModel<Void>(message: "解析失败", code: -1))
                    }
                    
//                    Log(response.request?.url?.absoluteString ?? "url没有获取到")
//                    Log(dict)
                    
                    guard let modelT = self.parsing(dict: dict) else {
                        print("转模型失败")
                        return failureCallback(BaseModel<Void>(message: "转模型失败", code: -1))
                    }
                    
                    if modelT.code == 6000 {
                        if let tabVC = GlobalTools.getWindow()?.rootViewController as? BaseTabBarViewController {
//                            tabVC.present(LoginNavigationViewController(), animated: true, completion: nil)
                        }
                    }
                    
                    if modelT.code == 200 {
                        successCallback(modelT.data)
                    }else {
                        ToastView.show(modelT.message)
                        failureCallback(modelT)
                    }
                    
                  
                }
                catch {
                    failureCallback(BaseModel<Void>(message: "获取数据失败", code: -1))
                }
            case .failure(_):
                //如果连接异常，则返沪错误信息（必要时还可以将尝试重新发起请求）
                //if target.shouldRetry {
                //    retryWhenReachable(target, successCallback, errorCallback,
                //      failureCallback)
                //}
                failureCallback(BaseModel<Void>(message: "接口异常", code: -1))
            }
        }
    }
    
   public static func dataToDictionary(data:Data) ->Dictionary<String, Any>?{
        do{
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

            let dic = json as! Dictionary<String, Any>

            return dic
        }catch _ {
            return nil
        }
    }
}

extension TargetType {
    //服务器地址
      public var baseURL: URL {
          URL(string: "http://10.1.1.14:10006")!
      }
    //各个请求的具体路径
        public var path: String {
            ""
        }
    
    
    //请求类型
    public var method: Moya.Method {
        .post
    }
    
    //请求任务事件（这里附带上参数）
    public var task: Task {
       .requestPlain
    }
    
    //是否执行Alamofire验证
       public var validate: Bool {
           return false
       }
    
    public var commonParmas: [String: Any] {
           return ["clientType" : "iOS",
                   "clientVersion" : Device.appVersion,
                   "deviceType" : Device.systemName,
                   "deviceCode" : Device.udid,
                   "deviceScreenSize" : Device.deviceScreenSize,
                   "deviceVersion" : Device.deviceVersion,
                   "macAddress" : "",
                   "networkType" : "",
                   "appPlatform" : "appStore",
                   "appBusinessCode" : "1",
                   "msgCode": self.path.components(separatedBy: "v1.0.0").last ?? ""
           ]
       }
    //这个就是做单元测试模拟的数据，只会在单元测试文件中有作用
    public var sampleData: Data {
        return "{}".data(using: String.Encoding.utf8)!
    }
    
    public var headers: [String : String]? {
        var header = ["Content-Type" : "application/json; charset=utf-8"]
        header["xq-token"] = LoginInformation.shared.token
        
        return header
    }
}

